// 渲染注册数据
function regRenter(data) {
    let userErr = $(".reg-box .userErr");

    if (data.code == 0) {
        alert(data.msp);
    } else if (data.code == 1) {
        userErr.innerHTML = data.msp;
    } else {
        alert(dara.msp);
    }
}


// 注册
function register() {
    let user = $(".reg-box .user");
    let pw = $(".reg-box .pw");
    let userErr = $(".reg-box .userErr");
    let pwErr = $(".reg-box .pwErr");
    let regBtn = $(".reg-box .reg-btn");

    regBtn.onclick = function(e) {
        e.preventDefault();
        let userVal = user.value;
        let pwVal = pw.value;

        // 验证有效性
        let html = "";
        if (/^[a-z]\w{5,11}$/i.test(userVal)) {
            html = '';
            user.flag = true;
        } else {
            html = '用户名必须是6-12位字母数字下划线，首字符必须是字母';
            user.flag = false;
        }
        userErr.innerHTML = html;

        if (/^[a-z\d]{6,8}$/i.test(pwVal)) {
            html = '';
            pw.flag = true;
        } else {
            html = '密码必须是6-8位字母数字';
            pw.flag = false;
        }
        pwErr.innerHTML = html;

        // 判断用户名和密码的有效性
        if (user.flag && pw.flag) {
            let url = `./api/reg.php?user=${userVal}&pw=${pwVal}`;
            ajax(url, regRenter);
        }

    }
}

// 渲染登陆数据
function loginRenter(data) {
    let userErr = $(".login-box .userErr");
    let pwErr = $(".login-box  .pwerr")

    if (data.code == 0) {
        alert(data.msp);
        location.href = 'http://localhost/04_login_register/01_admin_optimize/list.html';
    } else if (data.code == 0) {
        pwErr.innerHTML = data.msp;
    } else {
        userErr.innerHTML = data.msp;
    }
}

// 登陆 
function login() {
    let user = $(".login-box .user");
    let pw = $(".login-box .pw");
    let userErr = $(".login-box  .userErr");
    let pwErr = $(".login-box  .pwErr");
    let loginBtn = $(".login-box  .loginBtn");

    loginBtn.onclick = function(e) {
        e.preventDefault();
        let userVal = user.value;
        let pwVal = pw.value;

        // 验证有效性
        let html = "";
        if (/^[a-z]\w{5,11}$/i.test(userVal)) {
            html = '';
            user.flag = true;
        } else {
            html = '用户名必须是6-12位字母数字下划线，首字符必须是字母';
            user.flag = false;
        }
        userErr.innerHTML = html;

        if (/^[a-z\d]{6,8}$/i.test(pwVal)) {
            html = '';
            pw.flag = true;
        } else {
            html = '密码必须是6-8位字母数字';
            pw.flag = false;
        }
        pwErr.innerHTML = html;

        // 判断用户名和密码的有效性
        if (user.flag && pw.flag) {
            let url = `./api/login.php?user=${userVal}&pw=${pwVal}`;
            ajax(url, loginRenter);
        }

    }
}

register();
login();